<template>
  <div class="user-page">
    <mu-sub-header>用户列表</mu-sub-header>
    <!-- 用户表格 -->
    <abstract-table-page
      ref="pager"
      :fetcher="fetcher"
      :phone-columns="columns.phone"
      :pc-columns="columns.pc"
      @click-row="clickRow"
    >
      <template #default="{ row }">
        <td class="is-center">{{ row.id }}</td>
        <td class="is-center">{{ row.username }}</td>
        <td class="is-center">{{ row.realname }}</td>
        <td class="is-center">{{ roleToText(row.role) }}</td>
        <td class="is-center">{{ boolToText(row.is_superadmin) }}</td>
        <td class="is-center">{{ boolToText(row.is_active) }}</td>
        <td class="is-center">{{ toDatetimeString(row.register_at) }}</td>
        <td class="is-center">{{ toDatetimeString(row.last_login_at) }}</td>
        <td class="is-center">
          <mu-button class="user-action" color="primary" @click="handleEdit(row)">修改信息</mu-button>
          <mu-button class="user-action" color="lightBlue600" @click="handleChangePassword(row)">修改密码</mu-button>
          <mu-button class="user-action" color="orange800" @click="changeActive(row)">{{ row.is_active ? '禁用' : '解禁' }}</mu-button>
          <mu-button class="user-action" color="error" @click="handleRemoveUser(row)">删除</mu-button>
        </td>
      </template>
    </abstract-table-page>

    <!-- 编辑用户信息对话框 -->
    <mu-dialog title="用户信息编辑" width="640" :open.sync="showEditDialog" :esc-press-close="false" :overlay-close="false">
      <mu-flex align-items="center" class="form-line">
        <span class="form-line-item">用户ID：{{ form.id }}</span>
      </mu-flex>
      <mu-flex align-items="center" class="form-line">
        <span class="form-line-item">用户名：</span>
        <mu-radio v-model="form.use_username" class="form-line-item" value="off" label="不修改"></mu-radio>
        <mu-radio v-model="form.use_username" class="form-line-item" value="on" label="修改"></mu-radio>
        <mu-text-field v-if="form.use_username === 'on'" v-model="form.username" placeholder="请在这里新用户名"></mu-text-field>
      </mu-flex>
      <mu-flex align-items="center" class="form-line">
        <span class="form-line-item">真实姓名：</span>
        <mu-radio v-model="form.use_realname" class="form-line-item" value="off" label="不修改"></mu-radio>
        <mu-radio v-model="form.use_realname" class="form-line-item" value="on" label="修改"></mu-radio>
        <mu-text-field v-if="form.use_realname === 'on'" v-model="form.realname" placeholder="请在这里新真实姓名"></mu-text-field>
      </mu-flex>
      <mu-flex align-items="center" class="form-line">
        <span class="form-line-item">用户权限：</span>
        <mu-radio v-model="form.role" class="form-line-item" :value="0" label="无所属"></mu-radio>
        <mu-radio v-for="item in roles" :key="item.id" v-model="form.role" class="form-line-item" :value="item.id" :label="item.text"></mu-radio>
      </mu-flex>
      <mu-flex align-items="center" class="form-line">
        <span class="form-line-item">是否可用：</span>
        <mu-radio v-model="form.is_active" class="form-line-item" :value="true" label="是"></mu-radio>
        <mu-radio v-model="form.is_active" class="form-line-item" :value="false" label="否"></mu-radio>
      </mu-flex>
      <mu-button slot="actions" flat color="primary" @click="showEditDialog = false">取消</mu-button>
      <mu-button slot="actions" flat color="primary" @click="confirmEdit()">确定修改</mu-button>
    </mu-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { parseTime } from '@/util'
import { encryptPassword } from '@/api/password-client'
import AbstractTablePage from '@/components/AbstractTablePage'
import api from '@/api'

export default {
  name: 'UserPage',
  components: {
    AbstractTablePage
  },
  props: {
    fetcher: {
      type: Function,
      required: true
    }
  },
  data() {
    const makeColumns = marphWidth => ([
      { title: 'ID', name: 'id', width: 40, align: 'center' },
      { title: '用户名', name: 'username', width: marphWidth, align: 'center' },
      { title: '真实姓名', name: 'realname', width: marphWidth, align: 'center' },
      { title: '用户权限', name: 'role', width: 100, align: 'left' },
      { title: '超管', name: 'is_superadmin', width: 60, align: 'center' },
      { title: '启用', name: 'is_active', width: 40, align: 'center' },
      { title: '注册时间', name: 'register_at', width: 160, align: 'center' },
      { title: '最后登录', name: 'last_login_at', width: 160, align: 'center' },
      { title: '操作', name: 'actions', width: 250, align: 'center' }
    ])
    return {
      showEditDialog: false,
      form: {
        id: 0,
        use_username: 'off',
        username: '',
        use_realname: 'off',
        realname: '',
        role: 0,
        is_active: false
      },
      columns: {
        phone: makeColumns(200),
        pc: makeColumns(undefined)
      }
    }
  },
  computed: {
    ...mapGetters({
      publickey: 'publickey',
      isPhone: 'isPhone',
      types: 'types',
      pagin: 'pagin',
      roles: 'roles'
    })
  },
  methods: {
    // 刷新
    refresh() {
      this.$refs.pager.refresh()
    },
    // 权限编号转成文本
    roleToText(id) {
      if (id === 0) return '无隶属'
      const role = this.roles.find(it => it.id === id)
      return role ? role.text : '未知权限'
    },
    // 布尔值转文本
    boolToText(bool) {
      return bool ? '是' : '否'
    },
    // 时间字符串
    toDatetimeString(time) {
      return parseTime(time, '{y}-{m}-{d} {h}:{i}')
    },
    // 编辑用户信息
    handleEdit({ id, username, realname, role, is_active }) {
      this.form = {
        id,
        username,
        realname,
        role,
        is_active,
        use_username: 'off',
        use_realname: 'off'
      }
      this.showEditDialog = true
    },
    async confirmEdit() {
      try {
        await api.editUser(this.form.id, {
          username: this.form.username,
          realname: this.form.realname,
          role: this.form.role,
          is_active: this.form.is_active
        })
        this.$toast.success('编辑成功')
        this.refresh()
        this.showEditDialog = false
      } catch (err) {
        this.$apiCatch(err)
        this.showEditDialog = false
      }
    },
    // 修改密码
    handleChangePassword({ id }) {
      this.$prompt('请输入新密码', '提示', {
        validator(value) {
          return {
            valid: value && value.length > 3,
            message: '密码必须大于3个字'
          }
        },
        inputType: 'password'
      }).then(({ result, value }) => {
        if (result) {
          this.changePassword(id, value)
        } else {
          this.$toast.message('已取消')
        }
      })
    },
    async changePassword(id, password) {
      try {
        const payload = encryptPassword(this.publickey, password)
        await api.changeUserPassword(id, payload)
        this.$toast.success('密码已经成功修改')
      } catch (err) {
        this.$apiCatch(err)
      }
    },
    // 修改用户的可用状态
    async changeActive({ id, is_active }) {
      try {
        await api.editUser(id, {
          username: null,
          realname: null,
          role: null,
          is_active: !is_active
        })
        if (is_active) {
          this.$toast.success('已成功禁用用户')
        } else {
          this.$toast.success('已成功启用用户')
        }
        this.refresh()
      } catch (err) {
        this.$apiCatch(err)
      }
    },
    // 删除
    handleRemoveUser({ id }) {
      this.$confirm('删除不可恢复，确认？', '提示', {
        type: 'warning'
      }).then(({ result }) => {
        if (result) {
          this.removeUser(id)
        } else {
          this.$toast.message('已取消')
        }
      })
    },
    // 删除
    async removeUser(id) {
      try {
        await api.removeUser(id)
        this.$toast.success('删除成功')
        this.refresh()
      } catch (err) {
        this.$apiCatch(err)
      }
    }
  }
}
</script>

<style scoped>
.user-action {
  margin: 3px;
}
.form-line {
  padding-bottom: 8px;
}
.form-line-item {
  margin-right: 16px;
}
</style>
